<template>
  <div>
    <!--  :http-request="handleUpload" -->
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      :limit="1"
      accept=".mp4"
      :show-file-list="tags"
      :drag="true"
      :auto-upload="true"
      :http-request="handleUpload"
    >
      <div
        class="box"
        style="
          text-align: center;
          width: 360px;
          height: 180px;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
        "
      >
        <div>
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        </div>
        <div class="el-upload__text">
          将文件拖到此处，或<em style="color: var(--primary-color)"
            >点击上传</em
          >
        </div>
      </div>
    </el-upload>
  </div>
  <!-- 开始上传按钮 -->
</template>
<script setup>
const emit = defineEmits(['eventVideo']);
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import classRoom from '@/modules';
const { videoUploadApi } = classRoom;
const uploadRef = ref(null); // 用于访问上传组件的引用
import * as Qiniu from 'qiniu-js';
import { getQiniuUploadToken } from '@/api/upload.js';
const form = ref('');
const name = ref('');
const tags = ref(false);
const options = ref('');
// const uploadImgUrl = ref('https://up-z2.qiniup.com');
const handleUpload = async (option) => {
  options.value = option;
  name.value = option.file.name;
  tags.value = true;
  const { data } = await getQiniuUploadToken();
  const upToken = data[0].token;
  const config = {
    useCdnDomain: true,
    disableStatisticsReport: false,
    retryCount: 6,
    container: null,
    region: null,
  };
  const observable = Qiniu.upload(option.file, null, upToken, null, config);
  return observable.subscribe({
    next(resp) {
      option.onProgress({ percent: resp.total.percent });
    },
    error(err) {
      option.onError(err);
    },
    complete(resp) {
      // 上传成功后将文件名保存到form中
      form.value = 'https://mcdn.chatgk.com/' + resp.key;
      videoUpload(form.value, name.value);
      option.onSuccess(resp);
    },
  });
};
const videoUpload = async (url, name) => {
  const res = await videoUploadApi({ imgUrl: url, name: name });
  if (res.code == 20000) {
    ElMessage({
      message: res.msg,
      type: 'success',
    });
    emit('eventVideo', options.value, res.data, 'url', url);
  }
};
</script>
<style lang="scss" scope>
.box {
}
</style>
